<template>
    <div style="margin-top: 20px; width: 100%">
        <el-form :inline="true" :model="ruleForm" style="font-size: 15px; width: 100%" class="query-form">
            <div>
                <el-form-item label="分类名称">
                    <el-input v-model="page.classificationname" />
                </el-form-item>
                <el-form-item label="是否启用:" style="margin-left: -20px">
                    <el-radio-group v-model="page.isEnable">
                        <el-radio label="是" :value="1" />
                        <el-radio label="否" :value="0" />
                    </el-radio-group>
                </el-form-item>
            </div>
            <el-form-item>
                <el-button type="primary" @click="show">查询</el-button>
                <el-button type="primary" @click="empty">清空</el-button>
            </el-form-item>
        </el-form>
    </div>
    <div style="width: 100px">
        <el-button type="primary" @click="dialogFormVisible = true">新增</el-button>
    </div>

    <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="classificationname" label="分类名称" />
        <el-table-column prop="sort" label="排序" />
        <el-table-column prop="materialproduct" label="物料/产品" />
        <el-table-column prop="unit" label="是否启用">
            <template #default="scope">
                <el-text v-if="scope.row.isEnable === false" type="primary">否</el-text>
                <el-text v-else type="primary">是</el-text>
            </template>
        </el-table-column>
        <el-table-column prop="sTime" label="创建时间">
            <template #default="scope">
                {{ new Date(scope.row.sTime).toLocaleString() }}
            </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
            <template #default="scope">
                <el-button size="small" @click="editItem(scope.row)">编辑</el-button>
                <el-button size="small" @click="DelFrom(scope.row.parentId)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <div>
        <el-pagination v-model:current-page="page.PageIndex" v-model:page-size="page.PageSize"
            :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" :total="page.totalCount"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <div>
        <el-dialog v-model="dialogFormVisible" title="添加物料产品分类" width="1000">
            <el-form ref="ruleFormRef" style="max-width: 900px" :model="ruleForm" label-width="auto"
                class="demo-ruleForm" :size="formSize" status-icon>
                <el-form-item label="分类名称" prop="classificationname">
                    <el-input v-model="ruleForm.classificationname" />
                </el-form-item>
                <el-form-item label="显示排序" prop="sort">
                    <el-input-number v-model="ruleForm.sort" :min="1" :max="1000" />
                </el-form-item>
                <el-form-item label="产品/物料">
                    <el-radio-group v-model="ruleForm.materialproduct">
                        <el-radio :value="true" label="是">产品</el-radio>
                        <el-radio :value="false" label="否">物料</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="是否启用" prop="isEnable">
                    <el-radio-group v-model="ruleForm.isEnable">
                        <el-radio :value="true" label="是">是</el-radio>
                        <el-radio :value="false" label="否">否</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="AddForm(ruleFormRef)">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>

    <div>
        <el-dialog v-model="dialogFormVisible1" title="修改物料分类信息" width="1000">
            <el-form ref="ruleFormRef" style="max-width: 900px" :model="ruleForm" label-width="auto"
                class="demo-ruleForm" :size="formSize" status-icon>
                <el-form-item label="分类名称" prop="classificationname">
                    <el-input v-model="ruleForm.classificationname" />
                </el-form-item>
                <el-form-item label="显示排序" prop="sort">
                    <el-input-number v-model="ruleForm.sort" :min="1" :max="1000" />
                </el-form-item>
                <el-form-item label="产品/物料">
                    <el-radio-group v-model="ruleForm.materialproduct">
                        <el-radio :value="true" label="是">产品</el-radio>
                        <el-radio :value="false" label="否">物料</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="是否启用" prop="isEnable">
                    <el-radio-group v-model="ruleForm.isEnable">
                        <el-radio :value="true" label="是">是</el-radio>
                        <el-radio :value="false" label="否">否</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="UpdateForm(ruleFormRef)">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import axios from 'axios';
import { ElMessage, ElMessageBox, ElTable, ElTableColumn } from 'element-plus';
import { onMounted, ref, reactive } from 'vue';
import type { FormInstance } from 'element-plus';
const apiUrl = import.meta.env.VITE_APP_API_URL;
const tableData = ref([]);

// 查询表单数据
const page = reactive({
    PageIndex: 1,
    PageSize: 10,
    totalCount: 0,
    totalPage: 0,
    classificationname: '',
    isEnable: null,
});

// 整合显示、查询和分页的方法
const show = () => {
    axios.get(apiUrl + '/T5/ProductInfo/GetMaterialproductclassification', { params: page })
        .then((res) => {
            tableData.value = res.data.data;
            page.totalCount = res.data.totalCount;
            page.totalPage = res.data.totalPage;
        })
};

const empty = () => {
    page.classificationname = '',
    page.isEnable = null ,
    show();
};

const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`);
    page.PageSize = val;
    show();
};
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`);
    page.PageIndex = val;
    show();
};

//逻辑删除物料产品
const DelFrom = (parentId: any) => {
    ElMessageBox.confirm('确定要删除该物料产品吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            axios.put(apiUrl + '/T6/ProductInfos/DelMaterialproductclassification', { ParentId: parentId })
                .then((res) => {
                    if (res.data.code === 204) {
                        ElMessage.success('删除成功');
                        show();
                    } else {
                        ElMessage.error('删除失败，请稍后重试');
                    }
                })
                .catch((error) => {
                    console.error('删除物料产品失败:', error);
                    ElMessage.error('删除物料产品失败，请稍后重试');
                });
        })
        .catch(() => {
            // 用户取消删除操作
        });
};

const dialogFormVisible = ref(false);
const dialogFormVisible1 = ref(false);

interface RuleForm {
    parentId: 0,
    classificationname: string,
    sort: number,
    materialproduct: boolean,
    isEnable: boolean,
    sTime: Date,
    isDelete: boolean
    zId:number
}

const formSize = ref('default');
const ruleFormRef = ref<FormInstance>();
const ruleFormRef1 = ref<FormInstance>();

const ruleForm = reactive<RuleForm>({
    parentId: 0,
    classificationname: "",
    sort: 0,
    materialproduct: true,
    isEnable: true,
    sTime: new Date(),
    isDelete: false,
    zId:1
});

const AddForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            axios.post(apiUrl + "/T6/ProductInfos/AddMaterialproductclassification", ruleForm)
                .then(res => {
                    if (res.data.code === 100) {
                        ElMessage.success("添加成功!");
                        dialogFormVisible.value = false;
                        show();
                    } else {
                        ElMessage.error("添加失败，请稍后重试");
                    }
                })
                .catch((error) => {
                    console.error('添加物料产品失败:', error);
                    ElMessage.error('添加物料产品失败，请稍后重试');
                });
        } else {
            console.log('error submit!', fields);
            ElMessage.error('表单验证失败，请检查输入内容');
        }
    });
};

const editItem = (item: RuleForm) => {
    dialogFormVisible1.value = true;
    // 复制数据到表单
    Object.assign(ruleForm, item);
    // 确保日期格式正确
    ruleForm.sTime = new Date(item.sTime);
};

const UpdateForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            // 修改为使用 axios.put 方法
            axios.put(apiUrl + "/T6/ProductInfos/UpdateMaterialproductclassification", ruleForm)
                .then(res => {
                    if (res.data.code === 206) {
                        ElMessage.success("修改成功!");
                        dialogFormVisible1.value = false;
                        show();
                    } else {
                        ElMessage.error(`修改失败: ${res.data.message || '未知错误'}`);
                    }
                })
                .catch((error) => {
                    console.error('修改物料产品失败:', error);
                    ElMessage.error('修改物料产品失败，请稍后重试');
                });
        } else {
            console.log('error submit!', fields);
            ElMessage.error('表单验证失败，请检查输入内容');
        }
    });
};

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.resetFields();
};

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}));

onMounted(() => {
    show();
});
</script>
<style scoped></style>